<template>
  <div class="upload-container">
    <h2>关键词文件上传</h2>
    
    <el-upload
      class="upload-demo"
      drag
      :auto-upload="false"
      :on-change="handleFileChange"
      :on-remove="handleFileRemove"
      :file-list="fileList"
      accept=".xlsx,.xls,.csv"
      multiple
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          请上传.xls、.xlsx或.csv格式的关键词文件，可多选
        </div>
      </template>
    </el-upload>
    
    <div class="upload-actions">
      <el-button 
        type="primary" 
        @click="submitUpload" 
        :disabled="fileList.length === 0 || uploading"
        :loading="uploading"
      >
        {{ uploading ? '上传中...' : '上传文件' }}
      </el-button>
      <el-button @click="cancelUpload">取消</el-button>
    </div>
    
    <div v-if="uploadResult" class="upload-result">
      <el-alert
        :type="uploadResult.success ? 'success' : 'error'"
        :title="uploadResult.message"
        show-icon
        :closable="false"
      />
    </div>
  </div>
</template>

<script>
import { UploadFilled } from '@element-plus/icons-vue'
import { postRequest } from '../utils/request';
import axios from 'axios';

export default {
  name: 'KeywordUpload',
  components: {
    UploadFilled
  },
  data() {
    return {
      fileList: [],
      uploading: false,
      uploadResult: null
    }
  },
  methods: {
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
    },
    
    async submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择要上传的文件');
        return;
      }
      
      // Create a FormData object for each file
      const formDataList = this.fileList.map(fileObj => {
        const formData = new FormData();
        formData.append('file', fileObj.raw);
        return formData;
      });
      
      this.uploading = true;
      this.uploadResult = null;
      
      try {
        // Upload all files
        const uploadPromises = formDataList.map(formData => {
          const accessToken = localStorage.getItem('accessToken');
          return axios.post('/wow/keywords/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'access-token': accessToken
            }
          });
        });
        
        // Wait for all uploads to complete
        await Promise.all(uploadPromises);
        
        this.uploadResult = {
          success: true,
          message: `成功上传 ${this.fileList.length} 个文件`
        };
        
        this.$message.success(`成功上传 ${this.fileList.length} 个文件`);
        this.fileList = [];
      } catch (error) {
        const errorMessage = error.response?.data?.message || '文件上传失败';
        this.uploadResult = {
          success: false,
          message: errorMessage
        };
        
        this.$message.error(errorMessage);
      } finally {
        this.uploading = false;
      }
    },
    
    cancelUpload() {
      this.fileList = [];
      this.uploadResult = null;
    }
  }
}
</script>

<style scoped>
.upload-container {
  margin: 50px auto;
  max-width: 600px;
  padding: 20px;
}

.upload-actions {
  margin-top: 20px;
  text-align: center;
}

.upload-actions .el-button {
  margin: 0 10px;
}

.upload-result {
  margin-top: 20px;
}
</style>